<template>
  <view v-if="!loading">
    <!-- 查看合同 -->
    <view v-if="isLookContract" class="success-page_back">
      <uni-nav-bar fixed :border="false" background-color="transparent" left-icon="left" height="120rpx"
                   @clickLeft="isLookContract = false"></uni-nav-bar>
      <view class="card-container">
        <view class="title">{{ $t('bank.name.20') }}</view>

        <view class="text-box">
          <view class="user-info">
            <text>{{ $t('contract.text20') }}：{{ userDetails.contractNo }}</text>
            <text>{{ $t('contract.text1') }}：{{ getCurrentDate() }}</text>
            <text>
              {{ $t('contract.text2') }}
            </text>
            <text>{{ $t('contract.text22') }}：{{ userDetails.bankName }}</text>
            <!-- <text>{{ $t('contract.text3') }}：{{ userDetails.data.companyName }}</text> -->
            <text>{{ $t('contract.text4') }}：{{ userDetails.data.headquartersAddress }}</text>
            <text>{{ $t('contract.text7') }}：{{ userDetails.data.representativeName }}</text>
            <text>{{ $t('contract.text10') }}：{{ userDetails.data.registrationNumber }}</text>
            <text>{{ $t('contract.text5') }}</text>
            <!-- 公司贷款开始 -->
            <text v-if="isEnterprise">{{ $t('contract.text3') }}：{{ userDetails.enterpriseName }}</text>
            <text v-if="isEnterprise">{{ $t('contract.text6') }}：{{ userDetails.enterpriseAddress }}</text>
            <text v-if="isEnterprise">{{ $t('contract.text7') }}：{{ userDetails.legalName }}</text>
            <text v-if="isEnterprise">{{ $t('contract.text8') }}：{{ userDetails.legalPhone }}</text>
            <text v-if="isEnterprise">{{ $t('contract.text9') }}：{{ userDetails.businessLicenseNo }}</text>
            <!-- 公司贷款结束 -->
            <!-- 个人======贷款结束 -->
            <text v-if="!isEnterprise">{{ $t('contract.text11') }}：{{ userDetails.userName }}</text>
            <text v-if="!isEnterprise">{{ $t('contract.text12') }}：{{ userDetails.idCardNumber }}</text>
            <text v-if="!isEnterprise">{{ $t('contract.text13') }}：{{ userDetails.addressNow }}</text>
            <text v-if="!isEnterprise">{{ $t('contract.text14') }}：{{ userDetails.phoneNumber }}</text>
            <!-- 个人======贷款结束 -->
            <text>{{ $t('contract.text15') }} {{ addCommas(userDetails.approvedAmount) }}
              {{ $t('contract.text16') }} {{ userDetails.configCode }}% {{ $t('contract.text17') }}
              {{ userDetails.loanTerm }} {{ $t('apply.finally.title15') }}
              {{ $t('contract.text18') }} {{ userDetails.repaymentDate }}
              {{ $t('contract.text19') }}
            </text>

            <!-- ，自动从借方在[贷方xxxx]开立的以下还款账户中扣划当期应还款项目：
            <text>- 银行名称：xxxx</text>
            <text>- 账户号码：xxxx</text>
            <text>适用《银行信贷交易基本约定书》，并承诺遵守以下各项条款：</text> -->
          </view>
          <view class="item-text">
            <view v-html="contractText" class="des">
            </view>
          </view>
          <view class="checkbox-text" @click="isAgree = !isAgree">
            <checkbox :checked="isAgree" @click="isAgree = !isAgree" />{{ $t('bank.name.22') }}
          </view>
        </view>
        <button type="primary" class="bottom-btn" @click="onHttpSubmit">
          {{ $t('bank.name.6') }}
        </button>
      </view>
    </view>

    <view v-if="!isLookContract" class="success-page">
      <top-nav-bar backgroundColor="transparent" />
      <view class="icon-cark">
        <image :src="imageUrl" mode="widthFix" style="width: 100%; height: 100%"></image>
      </view>
      <view class="name">{{ stateName }}</view>
      <view v-if="stateData === '3'" class="num">
        <text>{{ $t('apply.success.title1') }}</text>
        <text>{{ formatKoreanWon(userDetails.approvedAmount) }}</text>
      </view>
      <view v-else class="des">{{ desName }}</view>
      <view v-if="stateData !== '3'" class="public-bottom_phone">
        <view class="phone" @click="onOpenChat">
          <uni-icons type="phone" size="20" color="#fff"></uni-icons>
        </view>
        <text class="phone-text" @click="onOpenChat">{{ $t('service.title') }}</text>
      </view>
      <button :style="{ 'margin-top': stateData === '3' ? '360rpx' : '82rpx' }" type="primary" class="bottom-btn"
              @click="onGo">
        {{ bottomBtnName }}
      </button>
    </view>

    <uni-popup ref="popup" title="还款内容" background-color="#fff">
      <view class="popup-box">
        <view class="title">
          <view class="name">{{ $t('repayment.title') }}</view>
          <uni-icons type="closeempty" size="20" @click="popup.close()"></uni-icons>
        </view>
        <view class="list-box">
          <view v-for="item in bottomList" :key="item.id" class="item-data">
            <view class="title">{{ item.repaymentDate }}</view>
            <view class="right-box">
              <text>{{ addCommas(item.principalAmount + item.interestAmount) }}</text>
              <text>{{ $t('repayment.principal') }} {{ addCommas(item.principalAmount) }}</text>
              <text>{{ $t('repayment.interest') }} {{ addCommas(item.interestAmount) }}</text>
            </view>
          </view>
        </view>
        <button type="primary" class="bottom-btn" @click="onJump">
          {{ $t('button.confirm') }}
        </button>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getApplyInfo, getApplyEnterprise, updateApply } from '@/api'
import { useI18n } from 'vue-i18n'
import { useChat } from '@/hooks/useChat'
import http from '@/utils/request.js'
import { getArticle } from '@/api'
import { useUser } from '@/hooks/useUser'

const { onOpenChat } = useChat()
const { formatKoreanWon, addCommas } = useUser()

const { t } = useI18n()

/** 是否查看合同 */
const isLookContract = ref(false)
/** 是否同意协议 */
const isAgree = ref(false)
const contractText = ref('')
const stateData = ref('')
/** 还款计划列表 */
const bottomList = ref([])
const userDetails = ref({})
const stateName = computed(() => {
  return {
    1: t('apply.complete'),
    3: t('apply.success.title3'),
    6: t('apply.title.18'),
    8: t('apply.complete.comment3'),
    4: t('apply.title.9'),
    9: t('apply.title.9'),
    10: t('apply.title.10'),
    11: t('apply.title.11'),
    13: t('apply.title.17'),
    15: t('apply.title.15'),
    16: t('apply.title.16'),
    17: t('apply.title.6')
  }[stateData.value]
})

const desName = computed(() => {
  return {
    1: t('apply.complete.comment'),
    6: t('apply.complete.comment4'),
    4: t('apply.title.4'),
    9: t('apply.title.5'),
    10: t('apply.title.5'),
    11: t('apply.title.5'),
    13: '',
    15: t('apply.title.7'),
    16: t('apply.title.14'),
    17: t('apply.complete.comment2')
  }[stateData.value]
})

const bottomBtnName = computed(() => {
  return {
    1: t('apply.complete.title'),
    3: t('button.confirm2'),
    6: t('apply.complete.title'),
    8: t('apply.complete.title'),
    4: t('apply.btn'),
    8: t('apply.title.13'),
    9: t('apply.complete.title'),
    10: t('apply.complete.title'),
    11: t('apply.complete.title'),
    13: t('apply.complete.title'),
    15: t('apply.title.8'),
    16: t('apply.btn'),
    17: t('apply.complete.title')
  }[stateData.value]
})

const imageUrl = computed(() => {
  return {
    1: '/static/success.svg',
    3: '/static/success.svg',
    6: '/static/date.svg',
    8: '/static/success.svg',
    4: '/static/no-icon.svg',
    9: '/static/no-icon.svg',
    10: '/static/no-icon.svg',
    11: '/static/no-icon.svg',
    13: '/static/success.svg',
    15: '/static/success.svg',
    16: '/static/no-icon.svg',
    17: '/static/date.svg'
  }[stateData.value]
})

const popup = ref(null)

const getCurrentDate = () => {
  const now = new Date()
  return now.toISOString().split('T')[0] // 输出格式：2025-09-23
}

/**
 * 跳转去二审输入信息页面
 * @param state 是否可编辑 1 可编辑 0 不可编辑
 */
const goInput = (state = 0) => {
  let queryData = ''
  if (state) {
    queryData = `?edit=1${isEnterprise.value ? '&type=enterprise' : ''}`
  } else {
    queryData = isEnterprise.value ? '?type=enterprise' : ''
  }

  uni.navigateTo({
    url: `/pages/id-card-input/id-card-input${queryData}`
  })
}

const onJump = () => {
  if (stateData.value === '8') {
    popup.value.close()
    return
  }
  // isEnterprise
  goInput()
}
const onGo = async () => {
  if (stateData.value === '16') {
    goInput(1)
    return
  }

  if (['3', '8'].includes(stateData.value)) {
    bottomList.value = await http.get('/api/service/loanMain/list', {
      id: userDetails.value.id,
      loanType: isEnterprise.value ? 2 : 1
    })
    popup.value.open('bottom')
    return
  }

  if (stateData.value === '4') {
    // isEnterprise.value
    uni.navigateTo({
      url: `/pages/apply-for/apply-for${isEnterprise.value ? '?type=enterprise' : ''}`
    })
    return
  }

  if (stateData.value === '15') {
    const res = await getArticle(isEnterprise.value ? 'Contract_Com' : 'Contract')
    contractText.value = res[0].articleDetails
    isLookContract.value = true
    return
  }

  uni.reLaunch({
    url: '/pages/index/index'
  })
}

const truncateDecimal = (num, decimalPlaces) => {
  const str = num.toString()
  const dotIndex = str.indexOf('.')
  if (dotIndex === -1) return num
  const endIndex = dotIndex + 1 + decimalPlaces
  return parseFloat(str.substring(0, endIndex))
}

const onHttpSubmit = async () => {
  if (!isAgree.value) {
    uni.showToast({
      title: t('bank.name.23'),
      icon: 'none'
    })
    return
  }

  const data = {
    ...userDetails.value,
    signDate: getCurrentDate(),
    status: 17
  }

  delete data.data

  await updateApply(data, isEnterprise.value)

  uni.redirectTo({
    url: `/pages/success-page/success-page?state=17${isEnterprise.value ? '&type=enterprise' : ''
      }`
  })
}

const isEnterprise = ref(false)
const loading = ref(true)
onLoad(async (e) => {
  try {
    loading.value = true
    // e.type === 'enterprise' 为企业申请
    const isShow = e.type === 'enterprise'
    isEnterprise.value = isShow
    const res = isShow ? await getApplyEnterprise() : await getApplyInfo()
    stateData.value = res.status + ''
    userDetails.value = {
      ...res,
      data: uni.getStorageSync('serviceInfo')
    }
    loading.value = false
  } catch (error) {
    loading.value = false
  }
})
</script>

<style lang="scss" scoped>
.success-page_back {
  background: url('/static/bg/bg-top.png') no-repeat top center, #e2ecf8;
  background-size: 100%;
}

.success-page {
  width: 100%;
  background: url('/static/bg/put.png') no-repeat top center;
  background-size: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .icon-cark {
    width: 436rpx;
    height: 436rpx;
    margin: 148rpx 0 10rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .name {
    font-family: PingFang SC, PingFang SC;
    font-weight: bold;
    font-size: 48rpx;
    color: #333333;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .num {
    margin-top: 48rpx;

    text {
      font-family: PingFang SC, PingFang SC;
      font-weight: bold;
      font-size: 24rpx;
      color: #666666;
      text-align: left;
      font-style: normal;
      text-transform: none;

      // 第二个
      &:nth-child(2) {
        margin: 0 12rpx;
        font-family: PingFang SC, PingFang SC;
        font-weight: bold;
        font-size: 64rpx;
        color: #3462fe;
        line-height: 64rpx;
        text-align: center;
        font-style: normal;
        text-transform: none;
      }
    }
  }

  .des {
    margin: 32rpx 0 128rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: bold;
    font-size: 24rpx;
    color: #666666;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .bottom-btn {
    width: 92%;
    height: 100rpx;
    line-height: 100rpx;
    background: #3462fe;
    border-radius: 64rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: bold;
    font-size: 32rpx;
    color: #ffffff;
    text-align: center;
    font-style: normal;
    text-transform: none;
  }
}

.popup-box {
  padding: 32rpx;

  button {
    margin: 20rpx 0 40rpx;
    width: 100%;
    border-radius: 60rpx;
  }

  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40rpx;

    .name {
      font-family: PingFang SC, PingFang SC;
      font-weight: bold;
      font-size: 40rpx;
      color: #333333;
      text-align: left;
      font-style: normal;
      text-transform: none;
    }
  }

  .list-box {
    max-height: 48vh;
    overflow-y: auto;

    .item-data+.item-data {
      padding-top: 30rpx;
    }

    .item-data {
      display: flex;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        width: 2rpx;
        height: 100%;
        background: #e2ecf8;
        left: 260rpx;
        top: 0;
      }

      .title {
        font-family: PingFang SC, PingFang SC;
        font-weight: 600;
        font-size: 32rpx;
        color: #333333;
        text-align: left;
        font-style: normal;
        text-transform: none;
        width: 260rpx;
      }

      .right-box {
        display: flex;
        flex-direction: column;
        padding-left: 80rpx;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          width: 18rpx;
          height: 18rpx;
          border-radius: 50rpx;
          background: #fff;
          border: 6rpx solid #3462fe;
          left: -14rpx;
          top: 28rpx;
          z-index: 1;
        }

        text {
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          font-size: 24rpx;
          color: #666666;
          text-align: left;
          font-style: normal;
          text-transform: none;

          &:first-child {
            font-weight: 600;
            font-size: 32rpx;
            color: #333333;
            margin-bottom: 10rpx;
          }
        }
      }
    }
  }
}

.card-container {
  padding: 32rpx;
  height: calc(100vh - 184rpx);

  .user-info {
    display: flex;
    flex-direction: column;
    margin-bottom: 20rpx;

    text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 26rpx;
      color: #444444;
      text-align: left;
      font-style: normal;
      text-transform: none;
      line-height: 40rpx;
    }
  }

  .title {
    margin-bottom: 48rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: bold;
    font-size: 40rpx;
    color: #333333;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .bottom-btn {
    margin: 120rpx 0 80rpx;
    height: 100rpx;
    line-height: 100rpx;
    background: #3462fe;
    border-radius: 64rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: bold;
    font-size: 32rpx;
    color: #ffffff;
    text-align: center;
    font-style: normal;
    text-transform: none;
  }

  .text-box {
    background: #fff;
    border-radius: 16rpx;
    padding: 28rpx 36rpx;

    .item-text {
      max-height: 57vh;
      overflow-y: auto;

      .des {
        max-height: 840rpx;
        overflow: auto;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        line-height: 42rpx;
        font-size: 28rpx;
        color: #999999;
        text-align: left;
        font-style: normal;
        text-transform: none;
      }
    }

    .checkbox-text {
      margin-top: 30rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 28rpx;
      color: #666666;
      text-align: left;
      font-style: normal;
      text-transform: none;
      display: flex;
      align-items: center;
    }
  }
}
</style>
